﻿using System;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using Strom.Core.Accounts;
using Strom.Core.Characters;
using System.IO;

namespace Strom.Core.Database
{
    public class BinaryDatabase
    {
        private const string AccFileName = "acc.bin";
        private const string CharsFileName = "chr.bin";

        private readonly BinaryFormatter _formatter;

        public List<Account> AccountsList { get; set; }
        public List<Character> CharactersList { get; set; }
        public AccountsManager AccountsManager { get; private set; }
        public CharactersManager CharactersManager { get; private set; }

        public BinaryDatabase()
        {
            AccountsList = new List<Account>();
            CharactersList = new List<Character>();
            _formatter = new BinaryFormatter();
        }

        #region Save and Load
        public void Load()
        {
            LoadCharacters();
            LoadAccounts();
            AccountsManager = new AccountsManager(this);
            CharactersManager = new CharactersManager(this);
        }

        public void Save()
        {
            SaveCharacters();
            SaveAccounts();
        }

        void LoadAccounts()
        {
            if(!File.Exists(AccFileName))
                return;

            using (var fs = File.Open(AccFileName, FileMode.Open))
                AccountsList = (List<Account>) _formatter.Deserialize(fs);
            
        }

        void LoadCharacters()
        {
            if (!File.Exists(CharsFileName))
                return;

            using (var fs = File.Open(CharsFileName, FileMode.Open))
                CharactersList = (List<Character>) _formatter.Deserialize(fs);
        }

        void SaveAccounts()
        {
            if(File.Exists(AccFileName))
                File.Delete(AccFileName);

            lock (AccountsList)
            {
                using (var fs = File.Create(AccFileName))
                    _formatter.Serialize(fs, AccountsList);
            }
        }

        void SaveCharacters()
        {
            if(File.Exists(CharsFileName))
                File.Delete(CharsFileName);

            lock (CharactersList)
            {
                using (var fs = File.Create(CharsFileName))
                    _formatter.Serialize(fs, CharactersList);
            }
        }
        #endregion
    }
}
